use anyhow::{Context, Result};
use teloxide::prelude2::*;
pub async fn start(_bot: AutoSend<Bot>, m: Message) -> Result<()> {
    let telegram_user = m.from().context("NoneError")?;
    let user_id = telegram_user.id;
    let user_username = telegram_user.username.clone();
    db::create_or_find_user(user_id, user_username).await?;
    Ok(())
}

mod db {
    use std::ops::Not;

    use anyhow::Result;
    use mongodb::bson::{doc, to_document, Document};

    use crate::user::UserBuilder;
    pub async fn check_user_exists(user_id: i64) -> Result<bool> {
        let db = crate::db::connect_to_db().await?;
        let coll = db.collection::<Document>("users");
        let filter = doc! {
        "telegramId": user_id
        };
        let res = coll.count_documents(filter, None).await?.gt(&0);
        Ok(res)
    }
    pub async fn create_user(user_id: i64, user_username: Option<String>) -> Result<()> {
        let joined = chrono::Utc::now();
        let id = uuid::Uuid::new_v4();
        let user = UserBuilder::builder()
            .id(id)
            .telegram_id(user_id)
            .telegram_username(user_username)
            .joined(joined.into())
            .show_real_url(false)
            .build();
        let db = crate::db::connect_to_db().await?;
        let coll = db.collection::<Document>("users");
        coll.insert_one(to_document(&user)?, None).await?;
        /*let inserted_id = coll
            .insert_one(to_document(&user)?, None)
            .await?
            .inserted_id
            .as_object_id()
            .context("NoneError")?;
        let filter = doc! {
            "_id": inserted_id
        };*/
        Ok(())
    }
    pub async fn create_or_find_user(user_id: i64, user_username: Option<String>) -> Result<()> {
        if check_user_exists(user_id).await?.not() {
            create_user(user_id, user_username).await?;
        }
        Ok(())
    }
}
